package cn.tramy.pinxian.task.query.listener

import cn.tramy.pinxian.common.util.logger
import cn.tramy.pinxian.task.domain.event.TaskCreated
import cn.tramy.pinxian.task.domain.event.TaskFinished
import cn.tramy.pinxian.task.query.dao.TaskEntryRepository
import cn.tramy.pinxian.task.query.entry.TaskEntry
import cn.tramy.pinxian.wind.event.annotation.EventHandler
import cn.tramy.pinxian.wind.event.annotation.EventHandlerAware
import cn.tramy.pinxian.wind.handler.HandleContext
import cn.tramy.pinxian.wind.util.gus
import org.springframework.beans.factory.annotation.Autowired

@EventHandlerAware
class TaskListener {

    @Autowired
    private lateinit var taskEntryRepository: TaskEntryRepository

    companion object {
        val LOGGER = logger(TaskListener::class.java)
    }

    @EventHandler
    fun onCreated(createdEvent: TaskCreated) {
        LOGGER.debug("on created: $createdEvent")
        TaskEntry(createdEvent.uid, createdEvent.content, createdEvent.timer, createdEvent.finished, createdEvent.createdAt).also { this.taskEntryRepository.save(it) }

    }

    @EventHandler(afterCommit = true)
    fun notifyExternal(createdEvent: TaskCreated, handleContext: HandleContext) {
        LOGGER.debug("on created for external: $createdEvent with command [${handleContext.getValue("COMMAND")}]")
    }

    @EventHandler
    fun onFinished(finished: TaskFinished) {
        LOGGER.debug("Task finished: $finished")
        gus(finished.uid, this.taskEntryRepository, { this.finished = true })
    }

}